<template>
  <div class="chat-content">
      <cu-header :height="80" class="chat-header"/>
      <!-- 聊天窗口 -->
      <div class="chat-out">
        <div class="chat">
            <!-- 显示聊天好友 -->
            <p class="target-user">{{chatPerson.name}}</p>
            <!-- 聊天列表 -->
            <div class="chat-list" id='chatList'>
                <div v-for="(item,index) in conversations" :key="index">
                    <div class="chat-inner-me" v-if="item.content.from_id === user.username">

                        <div>
                            <div class="text">{{item.content.msg_body.text}}</div>
                            <div style="color:#666;font-size:12px;margin-top:5px">{{format(item.content.create_time)}}</div>
                        </div>
                        <img class="user-head" :src="domain + user.avatar" alt="" />
                    </div>
                    <div class="chat-inner-other" v-if="item.content.from_id !== user.username">
                        <img class="user-head" :src="domain + chatPerson.avatar" alt="" />
                        <div>
                            <div class="text">{{item.content.msg_body.text}}</div>
                            <div style="color:#666;font-size:12px;margin-top:5px">{{format(item.content.create_time)}}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="chat-send">
                <input placeholder="Escreve uma mensagem..." class="textarea" :rows="3" type="textarea" v-model='forMsg' @keydown.enter="enterSend"/>
                <div style="text-align:right;margin:5px 10px 5px 0;" class="button">
                    <el-button size="mini"  @click="close">{{$t('component.conversation.2')}}</el-button>
                    <el-button size="mini" type="primary" @click="sendSingleMsg">{{$t('component.conversation.1')}}</el-button>
                </div>

            </div>
        </div>
        <div class="dialog-attention">
            <p class="attention">Dicas de Segurança</p>
            1,Mantém a conversa dentro do chat do Vivebo sempre que possível.<br />
            2,Evita pagar antecipadamente.<br />
            3,Verifica sempre o artigo antes de comprar.<br />
            4,Encontre o vendedor em um local público com o qual você esteja familiarizado<br />
        </div> 
      </div>
      
    <!-- <el-dialog title="Dicas de Segurança" :visible.sync="attentionVisible" width="40%" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
      <div class="dialog-attention">
        <p class="attention">Dicas de Segurança</p>
        1,Mantém a conversa dentro do chat do Vivebo sempre que possível.<br />
        2,Evita pagar antecipadamente.<br />
        3,Verifica sempre o artigo antes de comprar.<br />
        4,Encontre o vendedor em um local público com o qual você esteja familiarizado<br />
      </div>
      <div style="width: 100%;text-align: center">
        <el-button type="primary" @click="attentionVisible = false">Confirmar</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
import CuHeader from '@/components/header';
import JMessage from "@/assets/js/jmessage-sdk-web.2.6.0.min.js"
import md5 from 'blueimp-md5'
import { isLogin } from '@/utils';
import { Domain } from '@/constants';
import Api from '@/api';
export default {
  name: '',
  components:{CuHeader},
  data() {
    return {
      domain: Domain,
      user: {},
      JIM:new JMessage(),
      forMsg:"",
      chatPerson:{},
      //   对话列表
      conversations:[],
      timer:'',
      attentionVisible:true
    };
  },
  created() {
      if(this.$route.query.chatPerson){
          this.chatPerson = JSON.parse(this.$route.query.chatPerson)
      }
      console.log(this.$route.query.chatPerson)
      this.init()
  },
  mounted() {

  },
  beforeDestroy() {

  },
  methods: {
    //   重置会话未读数
      resetMsg(){
        this.JIM.resetUnreadCount({
            'username' : this.user.username
        });
      },
      init() {
        const that= this
        let timestamp = new Date().getTime()
        this.JIM.init({
                "appkey":"14ee52f19098774cb48d5505",
                "random_str":  "022cd9fd995849b",
                "signature":  md5(`appkey=14ee52f19098774cb48d5505&timestamp=${timestamp}&random_str=022cd9fd995849b&key=e3aea7056e6ef62b219ad578`),
                "timestamp": timestamp,
                "flag": 1
            }).onSuccess((data)=> {
                that.loadUserInfo();
                that.syncConversation()
                that.msgReceive()
        }).onFail(function(data) {
            console.log('error:' + JSON.stringify(data))
        });
      },
      loadUserInfo() {
        Api.loadUser().then((res) => {
            this.user = res;
            this.JIM.login({username:this.user.username,password:this.user.username}).onSuccess((data)=> {
                this.msgReceive()

                this.resetMsg()
                console.log('success:' + JSON.stringify(data));
            }).onFail((data)=>{
                console.log('error:' + JSON.stringify(data));
                this.msgReceive()
                this.resetMsg()
            });
        });
      },
    //   获取离线消息
    syncConversation(){
        // 离线消息监听
        this.JIM.onSyncConversation((dataSync)=> { //离线消息同步监听
            if (dataSync){
                dataSync.forEach(item => {
                    if(this.chatPerson.username == item.from_username){
                        this.conversations = item.msgs
                        this.resetMsg()
                    }
                })
            }
            // 改变视窗高度
             this.$nextTick(()=>{
                let chatWindow = document.getElementById('chatList')
                chatWindow.scrollTop = chatWindow.scrollHeight
            })
        });
    },
    // 聊天消息实时监听
    msgReceive(){
        this.JIM.onMsgReceive((data)=> {
            this.conversations.push(data.messages[0])
        });
    },
    // 发送消息
    sendSingleMsg() {
        // this.user.username
      this.isConnect()
      this.isLogin()
        this.JIM.sendSingleMsg({
            'target_username' : this.chatPerson.username,
			      'appkey' :  '14ee52f19098774cb48d5505',
            'content' : this.forMsg,
			       need_receipt:true
        }).onSuccess((data,msg)=> {
            this.isLogin()
            this.forMsg = ''
            this.conversations.push(msg)
            // 改变视窗高度
            this.$nextTick(()=>{
                let chatWindow = document.getElementById('chatList')
                chatWindow.scrollTop = chatWindow.scrollHeight
            })
        }).onFail(function(data) {
            console.log(data)
            console.log('error:' + JSON.stringify(data));
        });
    },
    // 回车键发送消息
    enterSend(){
        this.sendSingleMsg()
    },
    isConnect(){
	   console.log('isConnect:'+this.JIM.isConnect());
	},
	isInit(){
	  console.log('isInit:'+this.JIM.isInit());
	},
	isLogin(){
	   console.log('isLogin:'+this.JIM.isLogin());
	   return this.JIM.isLogin()
    },
    // 关闭聊天
    close(){
        this.$router.go(-1)
    },
    // 转换时间格式
   format(time){
       var date = new Date(time);
       var year=date.getFullYear(); 
        var month=date.getMonth()+1; 
        var date1=date.getDate(); 
        var h = date.getHours();
        var mm = date.getMinutes();
        var s = date.getSeconds();
        return year+"-"+month+"-"+date1+"  "+h+": "+mm+": "+s;
    }
  },
};
</script>
<style lang="scss" scoped>
.chat-content{
    height:100%;
    background-color: #f2f2f2;
    padding-bottom:40px;
    overflow: hidden;
    position: relative;
}
.chat-header{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2;
}
.chat-out{
    
    display: flex;
    width: 65%;
    margin: auto;
    margin-top: 100px;
}
.chat{
    background-color: #fff;
    width: 75%;
    // height: 60%;
    height: 550px;
    // border: 1px solid #fb8c24;
    margin: 40px auto;
    margin-top: 0;
    position: relative;
    border-radius: 10px;
    overflow: hidden;
    padding-bottom: 95px;

}
.target-user{
    color: #fff;
    background-color: #fb8c24;
    margin: 0;
    text-align: center;
    padding: 15px 0;font-size: 14px;
    letter-spacing: 1px;
    opacity: 0.8;
}
.chat-list{
    // height: calc(100% - 75px);
    height: 475px;
    overflow: auto;
    padding: 15px 0;
    .chat-inner-me{
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-right: 5px;
        margin-bottom: 10px;
        
        .text{
            font-size: 14px;
            margin-right: 5px;
            color: #fff;
            background-color: #fb8c24;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding:10px;
        }
    }
    .chat-inner-other{
        margin-left: 5px;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 10px;
        .text{
            font-size: 14px;
            margin-right: 5px;
            color: #fb8c24;
            background-color: #fff;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
           padding:10px;
           border: 1px solid #fb8c24;
        }
    }

}
.chat-send{
    width: 100%;
    border-top: 1px dashed #fb8c24;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    position: absolute;
    left: 0;
    bottom: 0;
    .button{
        width: 160px;
    }
    // .el-textarea{
    //     border-top:1px solid #fb8c24 !important;
    // }
    .textarea{
        margin-top: 5px;
        border: none;
        border: 1px solid #fb8c24;
        height: 80px;
        outline: none;
        font-size: 14px;
        padding: 0 5px;
        padding-left: 10px;
        border-bottom-left-radius: 10px;
        flex: 1;
    }
}
 .user-head {
    width: 32px;
    height: 32px;
    border-radius: 100%;
    margin-right: 5px;
    display: inline-block;
    background-color: #999999;
}
 .dialog-attention{
   width:25%;
   height: 645px;
   text-align:center;
   background-color: #fff;
   padding:0px 40px;
   padding-top: 0px;
   line-height: 28px;
   text-align: left;
   color: #595959;
   margin-left: 30px;
   border-radius: 10px;
   .attention{
     font-size: 18px;
     text-align: left;
   }
 }
</style>
